package com.nuo.backend.modules.security.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nuo.backend.modules.security.entity.SecRoleMenuEntity;
import com.nuo.backend.modules.security.service.SecMenuService;
import com.nuo.backend.modules.security.service.SecRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuo.backend.common.utils.PageUtils;
import com.nuo.backend.common.utils.Query;

import com.nuo.backend.modules.security.dao.SecRoleDao;
import com.nuo.backend.modules.security.entity.SecRoleEntity;
import com.nuo.backend.modules.security.service.SecRoleService;


@Service("secRoleService")
public class SecRoleServiceImpl extends ServiceImpl<SecRoleDao, SecRoleEntity> implements SecRoleService {

    @Autowired
    private SecRoleMenuService secRoleMenuService;

    @Autowired
    private SecMenuService secMenuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SecRoleEntity> page = this.page(
                new Query<SecRoleEntity>().getPage(params),
                new LambdaQueryWrapper<SecRoleEntity>()
                        .eq(ObjectUtil.isNotEmpty(params.get("createUserId")), SecRoleEntity::getCreateUserId, params.get("createUserId"))
        );
        page.getRecords().stream().forEach(
                i -> i.setSecMenuList(secMenuService.listByIds(secRoleMenuService.list(new LambdaQueryWrapper<SecRoleMenuEntity>().eq(SecRoleMenuEntity::getRoleId, i.getRoleId())).stream().map(SecRoleMenuEntity::getMenuId).collect(Collectors.toSet())))
        );
        return new PageUtils(page);
    }

    @Override
    public SecRoleEntity getById(Serializable id) {
        return super.getById(id).setSecMenuList(secMenuService.listByIds(secRoleMenuService.list(new LambdaQueryWrapper<SecRoleMenuEntity>().eq(SecRoleMenuEntity::getRoleId, id)).stream().map(SecRoleMenuEntity::getMenuId).collect(Collectors.toSet())));
    }
}